package com.stcc.base.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.stcc.base.bo.ResponseBase;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Slf4j
public class ReturnValueHandler implements HandlerMethodReturnValueHandler {

    public ReturnValueHandler() {
    }

    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getMethodAnnotation(ResponseBody.class) != null || returnType.getMethodAnnotation(ResponseBody.class) != null;
    }

    public void handleReturnValue(Object obj, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        Map<String, Object> rsp = new HashMap();
        modelAndViewContainer.setRequestHandled(true);
        HttpServletResponse response = (HttpServletResponse)nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType("application/json;charset=UTF-8");
        this.log.info("请求成功，返回消息转换");

        try {
            if (obj instanceof ResponseBase) {
                rsp.put("data", obj);
                if (StringUtils.isNotEmpty(((ResponseBase)obj).getCode())) {
                    rsp.put("code", ((ResponseBase)obj).getCode());
                    rsp.put("message", ((ResponseBase)obj).getMessage());
                } else {
                    rsp.put("code", "0");
                    rsp.put("message", "成功");
                }

                this.returnMsg(rsp, response);
            } else if (obj instanceof ResponseBase) {
                LinkedHashMap linkedHashMap = (LinkedHashMap)JSONObject.parseObject(this.objToJsonString(obj), LinkedHashMap.class, new Feature[]{Feature.OrderedField});
                JSONObject jsonObject = new JSONObject();
                jsonObject.putAll(linkedHashMap);
                if (jsonObject.size() == 1) {
                    Set<String> keySet = jsonObject.keySet();
                    Iterator var10 = keySet.iterator();

                    while(var10.hasNext()) {
                        String str = (String)var10.next();
                        Object o = jsonObject.get(str);
                        rsp.put("data", o);
                    }
                } else {
                    rsp.put("data", jsonObject);
                }

                if (StringUtils.isNotEmpty(((ResponseBase)obj).getCode())) {
                    rsp.put("code", ((ResponseBase)obj).getCode());
                    rsp.put("message", ((ResponseBase)obj).getMessage());
                } else {
                    rsp.put("code", "0");
                    rsp.put("message", "成功");
                }

                this.returnMsg(rsp, response);
            } else {
                rsp.put("code", "0");
                rsp.put("message", "成功");
                if (obj != null) {
                    rsp.put("data", obj);
                }

                this.returnMsg(rsp, response);
            }
        } catch (Exception var13) {
            this.log.info("转换信息失败，返回消息转换");
        }

    }

    private void returnMsg(Object msg, HttpServletResponse response) {
        PrintWriter writer = null;

        try {
            writer = response.getWriter();
            writer.write(this.objToJsonString(msg));
            writer.flush();
        } catch (IOException var8) {
            this.log.error("统一格式返回", var8);
        } finally {
            if (writer != null) {
                writer.close();
            }

        }

    }

    private String objToJsonString(Object msg) {
        return JSON.toJSONString(msg, new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse});
    }
}
